#include <SPI.h>
#include <Wire.h>
#include <Adafruit_AMG88xx.h>
#include <TFT.h>

Adafruit_AMG88xx amg;

//定义引脚
#define cs 10
#define dc 9
#define rst 8

//定义温度范围
#define MINTEMP 15 
#define MAXTEMP 40

TFT tft = TFT(cs, dc, rst);

struct temp{
    uint8_t R;
    uint8_t G;
    uint8_t B;
} Min, Max;

//设置像素
uint16_t displayPixelWidth,
         displayPixelHeight;

float pixels2[225];

void RGB_init(){
  Max.R = 0; Max.G = 0; Max.B = 255;
  Min.R = 255; Min.G = 0; Min.B = 0;
}

void simulate(float* pixels){
    for (int i = 0; i < 225;i++){
        int x = i / 15;
        int y = i % 15;
        if(x%2==0&&y%2==0)
            pixels2[i] = pixels[(x/2) * 8 + y/2];
        else if (x % 2 == 0 && y % 2 == 1)
                pixels2[i] = (pixels[(x / 2) * 8 + (y / 2)] + pixels[(x / 2) * 8 + (y / 2) + 1]) / 2;
        else if (x%2 == 1 && y%2 == 0)
                pixels2[i] = (pixels[(x / 2) * 8 + (y / 2)] + pixels[(x / 2+1) * 8 + (y / 2)]) / 2;
        else
            pixels2[i] = (pixels[(x / 2) * 8 + y / 2] + pixels[(x / 2) * 8 + y / 2 + 1] + pixels[(x / 2 + 1) * 8 + y / 2] + pixels[(x / 2 + 1) * 8 + y / 2 + 1]) / 4;
    }
}

struct temp get_RGB(float fac){
    struct temp index;
    index.R =(uint8_t)( Min.R * (1 - fac) + Max.R * fac);
    index.G =(uint8_t)( Min.G * (1 - fac) + Max.G * fac);
    index.B =(uint8_t)( Min.B * (1 - fac) + Max.B * fac);
    return index;
}

void AMG_init(){

    //调整波特率
    Serial.begin(9600);
    Serial.println(F("AMG88xx pixels"));

    bool status;

    //初始化
    status = amg.begin();
    if(! status) {
        Serial.println("Could not find a valid sensor.");
        while(1);
    }

    //设计标题
    Serial.println("-- Pixels Test --");
    Serial.println();

    //等待传感器启动
    delay(100);
}

//读取矩阵函数
void Amg_read(){
    float pixels[64];
    amg.readPixels(pixels);
    simulate(pixels);
        Serial.print("[");
    for (int i = 0; i < 225;i++){
        Serial.print(pixels2[i]);
        Serial.print(", ");
        if( (i+1)%15 == 0)
            Serial.println();
    }
    Serial.println("]");
    Serial.println();

    //设置帧率()
    delay(100);
}

void TFT_init(){
    tft.begin();
    tft.background(0, 0, 0);
    displayPixelHeight = tft.height() / 15;
    displayPixelWidth = tft.width() / 15;
}

//显示函数
void screen(){
    for (int i = 0; i < 225;i++){
        float kk = 1;
        float fac = (pixels2[i] - MINTEMP) / (MAXTEMP - MINTEMP);
        struct temp colorindex = get_RGB(fac);
        tft.fill(colorindex.R, colorindex.G, colorindex.B);
        tft.rect(kk*displayPixelHeight * floor (i/15),kk*displayPixelWidth * (i%15),kk*displayPixelHeight, kk*displayPixelWidth);
    }
}

void setup(){
  RGB_init();
  AMG_init();
  TFT_init();
}

void loop(){
  Amg_read();
  screen();
}